//
//  AppDelegate.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/1/16.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "AppDelegate.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

//微信SDK头文件
#import "WXApi.h"

//新浪微博SDK头文件
#import "WeiboSDK.h"
//新浪微博SDK需要在项目Build Settings中的Other Linker Flags添加"-ObjC"

#import "JPUSHService.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![[[Utility Share] VersionSelect] isEqualToString:[defaults valueForKey:@"guideVersion"]]) {
        //是否默认登录(清除密码)
        [defaults setValue:@"" forKey:default_userpwd];
        [defaults setValue:@"" forKey:default_userID];
        [defaults setValue:@"" forKey:default_userToken];
        [defaults synchronize];
        
    }else{
        
    }
    
    
    
    [[Utility Share] readUserInfoFromDefault];
    [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault];
    
    //kkNavigation
    UIStoryboard *story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    //根据 场景 标示符 ，创建目前视图对象
    CustomTabBar *tabbar=[story instantiateViewControllerWithIdentifier:@"CustomTabBarStoryboard"];
    [[Utility Share] setCustomTabBar_zk:tabbar];
    //把目标视图设置为根视图，切换到下一组 导航视图中
    self.window.rootViewController=tabbar;
    [self.window makeKeyAndVisible];
    
    
    // 3.0.0及以后版本注册可以这样写，也可以继续用旧的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:@"cac9ab96dd1d8f52b013c7bf"
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    
    
    
    
    
    if (![[[Utility Share] VersionSelect] isEqualToString:[defaults valueForKey:@"guideVersion"]]) {
        [defaults setValue:[[Utility Share] VersionSelect] forKey:@"guideVersion"];
        [defaults synchronize];
//        [[Utility Share] showStartGuideTransitionView];
//        
    }else{
    
        [[Utility Share]showStartTransitionView];
    }
    [self initShareSdkData];
    
    
    
    
    // Override point for customization after application launch.
    return YES;
}

-(void)initShareSdkData{
    /**
     *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册
     *  在将生成的AppKey传入到此方法中。
     *  方法中的第二个第三个参数为需要连接社交平台SDK时触发，
     *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
     *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
     */
    [ShareSDK registerActivePlatforms:@[@(SSDKPlatformSubTypeWechatSession),
                                       @(SSDKPlatformSubTypeWechatTimeline),
                                       @(SSDKPlatformTypeSinaWeibo),
                                       @(SSDKPlatformTypeQQ),
                                       @(SSDKPlatformTypeSMS),
                                       @(SSDKPlatformTypeMail)]
                             onImport:^(SSDKPlatformType platformType) {
                                 switch (platformType)
                                 {
                                     case SSDKPlatformTypeWechat:
                                         [ShareSDKConnector connectWeChat:[WXApi class]];
                                         break;
                                     case SSDKPlatformTypeQQ:
                                         [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                                         break;
                                     case SSDKPlatformTypeSinaWeibo:
                                         [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                                         break;
                                     default:
                                         break;
                                 }
                             } onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
                                 
                                 switch (platformType)
                                 {
                                     case SSDKPlatformTypeSinaWeibo:
                                         //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                                         [appInfo SSDKSetupSinaWeiboByAppKey:@"1570253341"
                                                                   appSecret:@"cca57e3f68e763c8bd5e7d027bb45254"
                                                                 redirectUri:@"http://www.sharesdk.cn"
                                                                    authType:SSDKAuthTypeBoth];
                                         break;
                                     case SSDKPlatformTypeWechat:
                                         [appInfo SSDKSetupWeChatByAppId:@"wxf80d7ebe2e5ffd85"
                                                               appSecret:@"a8c51914565395478ab8aba06c3811e8"];
                                         break;
                                     case SSDKPlatformTypeQQ:
                                         [appInfo SSDKSetupQQByAppId:@"1105878247"
                                                              appKey:@"2hylLdFKIN9G5DyK"
                                                            authType:SSDKAuthTypeBoth];
                                         break;
                                     default:
                                         break;
                                 }
                             }];
    
//    [ShareSDK registerApp:@"1ae17004092e9"
//     
//          activePlatforms:@[@(SSDKPlatformSubTypeWechatSession),
//                            @(SSDKPlatformSubTypeWechatTimeline),
//                            @(SSDKPlatformTypeSinaWeibo),
//                            @(SSDKPlatformTypeQQ),
//                            @(SSDKPlatformTypeSMS),
//                            @(SSDKPlatformTypeMail)]
//                 onImport:^(SSDKPlatformType platformType)
//     {
//         switch (platformType)
//         {
//             case SSDKPlatformTypeWechat:
//                 [ShareSDKConnector connectWeChat:[WXApi class]];
//                 break;
//             case SSDKPlatformTypeQQ:
//                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
//                 break;
//             case SSDKPlatformTypeSinaWeibo:
//                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
//                 break;
//             default:
//                 break;
//         }
//     }
//          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
//     {
//         
//         switch (platformType)
//         {
//             case SSDKPlatformTypeSinaWeibo:
//                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
//                 [appInfo SSDKSetupSinaWeiboByAppKey:@"1570253341"
//                                           appSecret:@"cca57e3f68e763c8bd5e7d027bb45254"
//                                         redirectUri:@"http://www.sharesdk.cn"
//                                            authType:SSDKAuthTypeBoth];
//                 break;
//             case SSDKPlatformTypeWechat:
//                 [appInfo SSDKSetupWeChatByAppId:@"wxf80d7ebe2e5ffd85"
//                                       appSecret:@"a8c51914565395478ab8aba06c3811e8"];
//                 break;
//             case SSDKPlatformTypeQQ:
//                 [appInfo SSDKSetupQQByAppId:@"1105878247"
//                                      appKey:@"2hylLdFKIN9G5DyK"
//                                    authType:SSDKAuthTypeBoth];
//                 break;
//             default:
//                 break;
//         }
//     }];
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    DLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSDictionary * userInfo = notification.request.content.userInfo;
        DLog(@"iOS10 前台收到远程通知:");
        [self logDic:userInfo];
        
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        DLog(@"iOS10 收到远程通知:");
        if ([[Utility Share] isUserLogin]) {
            [[Utility Share] setIsPushMessage:NO];
            SendNotify(@"JPushMessage", userInfo)
        }else{
            [[Utility Share] setIsPushMessage:YES];
            [[Utility Share] setUserPushData:userInfo];
        }
        [self logDic:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    DLog(@"收到通知a" );
    if (application.applicationState == UIApplicationStateActive) {
        DLog(@"程序当前正处于前台");
        [self logDic:userInfo];
        //程序当前正处于前台
        
    }
    else if(application.applicationState == UIApplicationStateInactive)
    {
        DLog(@"程序处于后台");
        if ([[Utility Share] isUserLogin]) {
            [[Utility Share] setIsPushMessage:NO];
            SendNotify(@"JPushMessage", userInfo)
        }else{
            [[Utility Share] setIsPushMessage:YES];
            [[Utility Share] setUserPushData:userInfo];
        }
        [self logDic:userInfo];
        
    }else{
        
    }
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}


- (void)logDic:(NSDictionary *)dic {
    DLog(@"pushDic:%@",dic);
    NSDictionary * data = dic[@"extras"];
    if ([[data valueForJSONStrKey:@"type"] isEqualToString:@"2"]) {
        
        [QAlertView showAlertViewWithTitle:[data valueForJSONStrKey:@"txt"] message:@"" cancelButtonTitle:@"确定" OtherButtonsArray:nil clickAtIndex:^(NSInteger index) {
            
        }];
    }
    
}

@end
